package traverser;

import javax.swing.JOptionPane;

public class KeywordFirstTraversal {
	KeyTracker tracker;
	CacheLinkProcessor lp;
	String linkStart;
	String linkEnd;
	long t1,t2,period;
	boolean ifFound=false;
    String nextLink;
	int lastLinkPriority=0;   //record the priority of the last link to distinguish if two links have same content even if they have different names
    int[] visited=new int[100];
    int visitedNum=0;
	// Queue<String> result;
    
    
	
	public KeywordFirstTraversal(String linkStart,String linkEnd){
		tracker=new KeyTracker(linkEnd, true);  //store the keyword of the end page as hashmap
		this.linkStart=linkStart;
		this.linkEnd=linkEnd;
		//result.push(this.linkStart);
		t1=System.currentTimeMillis();
		System.out.println("Start: "+linkStart);
		for(int i=0;i<100;i++) visited[i]=0;
		run();
	}
    
	// TODO: this happens to coincide with the namespace used by the thread library.
	//  Renaming is not nessecary but would be good.
	public void run(){
		
		nextLink=findPriority(linkStart);
	//	result.push(nextLink);
		while(ifFound==false){
		    nextLink=findPriority(nextLink);
	//		result.push(nextLink);
		}
		System.out.println("Found the end page "+nextLink);
		//System.out.println("");
		//System.out.println("Final Result: ");
		//int resultCount=result.size();
		//for(int i=0;i<resultCount;i++){
		//	System.out.println(i+": "+result.pop());
		//}
		
	}
	
	public String findPriority(String link){

		lp=new CacheLinkProcessor(link);
		String[] links=new String[lp.count()];
		int[] linkPriority=new int[lp.count()];
		lp.removeDuplicates();
		links=lp.getLinks();
	
		
         for(int i=0;i<lp.count();i++){      //to see if the target page has been found. It saves time to write it here than do it in the loop behind.
			
			if(links[i].equals(linkEnd)){   // Found the target page!!
				ifFound=true;
				 t2=System.currentTimeMillis();
				 period = t2-t1;
				System.out.println("Time spent on it: "+period);
				return links[i];
			}
		
         }
		
		
		for(int i=0;i<lp.count();i++){  //visit each link of page linkStart
			
			//TODO: Perhaps temp is not the best name for this
			CacheLinkProcessor temp=new CacheLinkProcessor(links[i]);      
			int priority=0;
			String[] tempLink=temp.getLinks();
			String[][] tempKey=new String[temp.count()][];
			
			// TODO: same problem here as in KeyTracker - perhaps make this a method somewhere
			for(int j=0;j<tempLink.length;j++){     //the keyword of next layer links
				
				String tempString=tempLink[j];
				tempString=tempString.substring(29,tempString.length());

				tempString=tempString.replace("of_","");
				tempString=tempString.replace("the_","");
				tempString=tempString.replace("and_","");
				tempString=tempString.replace("with_","");
				tempString=tempString.replace("or_","");
				tempString=tempString.replace("or_","");
				tempString=tempString.replace("(","");
				tempString=tempString.replace(")","");
				tempString=tempString.replace("%27","'");
				tempString=tempString.toLowerCase();
				tempKey[j]=tempString.split("_");			
			}


			/*	for(int j=0;j<tempKey.length;j++){                    
				for(int k=0;k<tempKey[j].length;k++){
					System.out.println(tempKey[j][k]);
				}
			}
			 */
			
			// compute the priority of each link and store in the linkPriority array
			for(int j=0;j<tempKey.length;j++){                     
				for(int k=0;k<tempKey[j].length;k++){
					// int prio=tracker.returnHashmap(tempKey[j][k]);
					//	System.out.print(prio+" ");
					priority+=tracker.priorityOf(tempKey[j][k]);
				}
			}
	        System.out.println(links[i]+" has priority "+priority);
			linkPriority[i]=priority;

		}
        
		//sort out page according to their priorities
		//TODO: use a more efficient sort algorithm
		for(int i=0;i<lp.count();i++){
			for(int j=i+1;j<lp.count();j++){
				if(linkPriority[i]<linkPriority[j]){
					int tempA=linkPriority[i];
					int tempB=linkPriority[j];
					linkPriority[i]=tempB;
					linkPriority[j]=tempA;
					String tempLinkA=links[i];
					String tempLinkB=links[j];
					links[i]=tempLinkB;
					links[j]=tempLinkA;
				}				
			}			
		}
		
		
		
		
		
		
	/*	int maxPriority=0;
		int secondMax=0;
		for(int i=0;i<p.count();i++){
			if(linkPriority[maxPriority]<linkPriority[i])   maxPriority=i;
		}
		for(int i=0;i<p.count();i++){
			if((linkPriority[secondMax]<linkPriority[i])&&(linkPriority[i]<linkPriority[maxPriority]))   secondMax=i;
		}
		*/
        
		//if highest priority page equals the original page then return the second highest page
		
		boolean ifReturn=false;
		int num=0;
		while(!ifReturn){
			if(links[num].equals("http://en.wikipedia.org/wiki/Main_Page")||ifVisited(linkPriority[num])) num++;
			else ifReturn=true;			
		}
		System.out.println("Visit "+links[num]+ " with a priority of "+linkPriority[num]);
		
		visited[visitedNum]=linkPriority[num];
		visitedNum++;
		JOptionPane.showMessageDialog(null,"Visit "+links[num]+ " with a priority of "+linkPriority[num],null,JOptionPane.INFORMATION_MESSAGE);
		return links[num];
		
	/*	if((linkPriority[maxPriority]==lastLinkPriority)||links[maxPriority].equals("http://en.wikipedia.org/wiki/Main_Page")){
			System.out.println("Visit "+links[secondMax]+ " with a priority of "+linkPriority[secondMax]);
			lastLinkPriority=linkPriority[secondMax];
	        return links[secondMax];  //start visit next link
		}
		else{
			lastLinkPriority=linkPriority[maxPriority];
		System.out.println("Visit "+links[maxPriority]+ " with a priority of "+linkPriority[maxPriority]);
        return links[maxPriority];  //start visit next link
		}
		*/

	}
	
	// check if this page is in the path
	public boolean ifVisited(int n){
		boolean ifVisited=false;
		for(int i=0;i<100;i++){
			if(n==visited[i]) ifVisited=true;			
		}
		return ifVisited;		
	}
	
	
	public static void main(String[] args){
		/*
		String link_start="http://en.wikipedia.org/wiki/Silvio_Berlusconi";
		String link_end="http://en.wikipedia.org/wiki/Urticina_lofotensis";
		*/
		String link_start="http://en.wikipedia.org/wiki/Photograph";
		String link_end="http://en.wikipedia.org/wiki/Apple";
		
		KeywordFirstTraversal k=new KeywordFirstTraversal(link_start,link_end);
	}

}
